package com.dwxt.cdms.service;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.dwxt.cdms.api.common.utils.StringUtil;
import com.dwxt.cdms.constant.EquipCategory;
import com.dwxt.cdms.constant.MessageType;
import com.dwxt.cdms.dao.*;
import com.dwxt.cdms.dao.yumeng.*;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.*;
import com.dwxt.cdms.entity.oufu.OuFuData;
import com.dwxt.cdms.entity.oufu.OuFuDataExample;
import com.dwxt.cdms.entity.yumeng.*;
import com.dwxt.cdms.listener.LbWebSocketClient;
import com.dwxt.cdms.service.wx.WxMessageService;
import com.dwxt.cdms.util.BirthDayUtil;
import com.dwxt.cdms.util.RedisUtil;
import com.dwxt.cdms.util.SimpleCalendar;
import com.dwxt.cdms.util.UtilDao.Point;
import com.dwxt.cdms.view.EquipmentCustomView;
import com.dwxt.common.constant.VariableConstants;
import com.dwxt.common.util.SnowIdUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

@Service
@Slf4j
public class TaskService {

    @Autowired
    private ReceiveDataMapper receiveDataMapper;

    @Autowired
    private EquipmentCustomService equipmentCustomService;

    @Autowired
    private StepDataMapper stepDataMapper;

    @Autowired
    private HealthService healthService;

    @Autowired
    private BpDataMapper bpDataMapper;

    @Autowired
    private HrDataMapper hrDataMapper;

    @Autowired
    private LocDataMapper locDataMapper;

    @Autowired
    private ElectronicFenceService electronicFenceService;

    @Autowired
    private WarningService warningService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private HealthSummaryService healthSummaryService;

    @Autowired
    private HealthSummaryYearService healthSummaryYearService;

    @Autowired
    private BirthdayMapper birthdayMapper;

    @Autowired
    private HealthWarnRecordMapper healthWarnRecordMapper;

    @Autowired
    private WarningMapper warningMapper;

    @Autowired
    private IAcsClient iAcsClient;

    @Autowired
    private SendSmsRequest sendSmsRequest;

    @Autowired
    private OuFuDataBandSleepMapper bandSleepMapper;

    @Autowired
    private EquipmentCustomMapper equipmentCustomMapper;

    @Autowired
    private LbWatchService lbWatchService;

    @Autowired
    private HealthReportService healthReportService;

    @Autowired
    private TaskMessageService taskMessageService;

    @Autowired
    private WxMessageService wxMessageService;

    @Transactional
    public void pullWatchData(String result) {
        JSONObject object = JSONObject.fromObject(result);
        int code = object.getInt("code");
        if (code == 0) {
            //插入原始数据
            String receiveId = SnowIdUtil.getInstance().nextId();
            ReceiveData receiveData = new ReceiveData()
                    .setId(receiveId)
                    .setCreateTime(LocalDateTime.now())
                    .setType("watch")
                    .setReceiveData(result);
            receiveDataMapper.insert(receiveData);
            //插入健康数据
            JSONArray jsonArray = object.getJSONArray("data");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                int state = jsonObject.getInt("state");
                if (state == 1) {
                    String deviceId = jsonObject.getString("deviceId");
                    //步数
                    String steps = jsonObject.getString("steps");
                    //血氧
                    String spo2FromWatch = jsonObject.getString("spo2FromWatch");
                    //血压
                    String bloodFromWatch = jsonObject.getString("bloodFromWatch");
                    //心率
                    String heartFromWatch = jsonObject.getString("heartFromWatch");
                    //位置
                    String positon = jsonObject.getString("positon");
                    //经纬度
                    String ne = jsonObject.getString("ne");
                    //插入计步数据
                    insertStep(receiveId, deviceId, steps);
                    //插入血氧，血压数据
                    insertO2(receiveId, deviceId, spo2FromWatch, bloodFromWatch);
                    //插入心率
                    insetHeart(receiveId, deviceId, heartFromWatch);
                    //插入定位数据
                    insertLoc(receiveId, deviceId, ne);
                }
            }
        }
    }

    private void insertLoc(String receiveId, String deviceId, String ne) {
        String lon = null;
        String lat = null;
        if (StringUtil.isNotBlank(ne)) {
            String[] split = ne.split(",");
            lon = split[1];
            lat = split[0];
        }
        LocData locData = new LocData();
        locData.setReceiveDataId(receiveId).setDeviceIdentity(deviceId).setLongitude(lon).setLatitude(lat)
                //.setTime(DateUtil.timeStrStamp2TimeStr(locData.getTime()))
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0);

        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceId);
        if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
            locData.setCustomerId(equipmentCustom.getCustomerId());
            locDataMapper.insert(locData);
            //电子围栏报警
            ElectronicFence electronicFence = electronicFenceService.selectFenceByCustomerId(equipmentCustom.getCustomerId());
            if (electronicFence != null && electronicFence.getStatus() == 1) {
                Point point = new Point(Double.valueOf(locData.getLongitude()), Double.valueOf(locData.getLatitude()));
                boolean warning = electronicFenceService.isWarning(point, equipmentCustom.getCustomerId());
                if (warning) {
                    warningService.insertWarningElectronic(locData);
                }
            }
        }
    }

    private void insetHeart(String receiveId, String deviceId, String heartFromWatch) {
        Integer hr = null;
        if (StringUtil.isNotBlank(heartFromWatch)) {
            hr = Integer.parseInt(heartFromWatch);
        }
        HrData hrData = new HrData();
        hrData.setReceiveDataId(receiveId)
                .setHr(hr).setDeviceIdentity(deviceId)
                //.setTime(DateUtil.timeStrStamp2TimeStr(hrData.getTime()))
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0);

        //加入客户id
        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceId);
        if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
            hrData.setCustomerId(equipmentCustom.getCustomerId());
            healthService.judgeIsNormalAndInsertRecord(hrData);
            hrDataMapper.insert(hrData);
        }

    }

    private void insertO2(String receiveId, String deviceId, String spo2FromWatch, String bloodFromWatch) {
        Integer gy = null;
        Integer dy = null;
        Integer o2 = null;
        if (StringUtils.isNotBlank(bloodFromWatch)) {
            String[] split = bloodFromWatch.split(",");
            gy = Integer.parseInt(split[0]);
            dy = Integer.parseInt(split[1]);
        }
        if (!"null".equalsIgnoreCase(spo2FromWatch) && null != spo2FromWatch) {
            o2 = Integer.parseInt(spo2FromWatch);
        }
        BpData bpData = new BpData();
        bpData.setReceiveDataId(receiveId).setDeviceIdentity(deviceId)
                .setSystolic(gy)
                .setDiastolic(dy).setOxygen(o2)
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0);

        //加入客户id
        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceId);
        if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
            bpData.setCustomerId(equipmentCustom.getCustomerId());
            healthService.judgeIsNormalAndInsertRecord(bpData);
            bpDataMapper.insert(bpData);
        }

    }

    private void insertStep(String receiveId, String deviceId, String steps) {
        Integer step = null;
        if (StringUtil.isNotBlank(steps)) {
            step = Integer.parseInt(steps);
        }
        StepData stepData = new StepData();
        stepData.setReceiveDataId(receiveId).setStepNumber(step).setDeviceIdentity(deviceId)
                .setId(SnowIdUtil.getInstance().nextId())
                .setCreateTime(LocalDateTime.now())
                .setIsDelete(VariableConstants.STRING_CONSTANT_0);
        //int count = stepDataMapper.countStepDataByCondition(stepData);

        //加入客户id
        //String deviceIdentity = stepData.getDeviceIdentity();
        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(deviceId);
        if (equipmentCustom != null && equipmentCustom.getCustomerId() != null) {
            stepData.setCustomerId(equipmentCustom.getCustomerId());
            stepDataMapper.insert(stepData);
        }

    }

    public void generateTask() {
        //生成季度报告
        //查询大于3个月的用户
        List<com.dwxt.cdms.entity.Customer> customerList = customerService.selectOverThreeMonth();
        for (Customer customer : customerList) {
            //查询最近的季度总结
            HealthSummary healthSummary = healthSummaryService.selectLastRecord(customer.getId());
            if (healthSummary == null) {
                healthSummary = new HealthSummary();
                healthSummary.setCount(1);
                healthSummary.setCustomerId(customer.getId());
                healthSummary.setSerialNumber(customer.getFileNumber());
                healthSummary.setCustomerName(customer.getName());
                healthSummary.setPhone(customer.getPhone());
                healthSummaryService.insertSelective(healthSummary);
            } else {
                //时间又过去3个月
                if (healthSummary.getCreateTime().getTime() + (long) 90 * 24 * 60 * 60 * 1000 < System.currentTimeMillis()) {
                    HealthSummary summary = new HealthSummary();
                    summary.setCount(healthSummary.getCount() + 1);
                    summary.setCustomerId(customer.getId());
                    summary.setSerialNumber(customer.getFileNumber());
                    summary.setCustomerName(customer.getName());
                    summary.setPhone(customer.getPhone());
                    healthSummaryService.insertSelective(summary);
                }
                //生成年度报告
                if (healthSummary.getCount() % 4 == 0) {
                    int count = healthSummary.getCount() / 4;
                    //查询最近的年度总结
                    HealthSummaryYear healthSummaryYear = healthSummaryYearService.selectLastRecord(customer.getId());
                    if (healthSummaryYear == null || healthSummaryYear.getCount() < count) {
                        healthSummaryYear = new HealthSummaryYear();
                        healthSummaryYear.setCount(count);
                        healthSummaryYear.setCustomerId(customer.getId());
                        healthSummaryYear.setSerialNumber(customer.getFileNumber());
                        healthSummaryYear.setCustomerName(customer.getName());
                        healthSummaryYear.setPhone(customer.getPhone());
                        healthSummaryYearService.insertSelective(healthSummaryYear);
                    }
                }
            }
        }

    }

    public void addAndDeleteBirthday() {
        //删除
        delete();
        //插入
        insert();
    }

    private void insert() {
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        List<Customer> customerList = customerService.selectIdNumberNotNull();
        for (Customer customer : customerList) {
            try {
                Date birthday = BirthDayUtil.getBirthdayByIDNumber(customer.getIdNumber());
                calendar.setTime(birthday);
                int month = calendar.get(Calendar.MONTH) + 1;
                int day = calendar.get(Calendar.DAY_OF_MONTH);
                Date date = simpleDateFormat.parse(year + "-" + month + "-" + day);
                //生日前3天
                if (currentTimeMillis > date.getTime() - (long) 3 * 24 * 60 * 60 * 1000 && currentTimeMillis < date.getTime()) {
                    Birthday birth = new Birthday();
                    birth.setCustomerId(customer.getId());
                    birth.setDay(day);
                    birth.setMonth(month);
                    birth.setYear(calendar.get(Calendar.YEAR));
                    birth.setIdNumber(customer.getIdNumber());
                    birthdayMapper.insertSelective(birth);
                }
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
    }

    private void delete() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        BirthdayExample example = new BirthdayExample();
        example.createCriteria().andMonthLessThan(month);
        BirthdayExample.Criteria criteria = example.createCriteria().andMonthEqualTo(month).andDayLessThan(day);
        example.or(criteria);
        birthdayMapper.deleteByExample(example);
    }

    public void putMessage() throws ParseException {
        Date end = new Date();
        Long amount = 1000 * 60 * 30L;
        Date start = getDate(end, amount);

        // 查询是否有新数据
        Integer count = healthWarnRecordMapper.getAllCount();
        Integer healthCount = RedisUtil.get("healthCount", Integer.class);
        if (healthCount == null || count > healthCount) {
            RedisUtil.set("healthCount", count, 60 * 30L);
            // 查询心率数据
            List<HealthWarnRecord> highWarnRecords = healthWarnRecordMapper.findHighHeart(start, end);
            if (highWarnRecords.size() > 0) {
                for (HealthWarnRecord highWarnRecord : highWarnRecords) {
                    String detail = highWarnRecord.getDetail();
                    String replace = detail.replace("脉搏 (", "");
                    String heartNum = replace.replace(") 异常", "");
                    String warnId = RedisUtil.get(String.valueOf(highWarnRecord.getId()), String.class);
                    if (Integer.parseInt(heartNum) > 120) {
                        if (warnId == null) {
                            saveMessage(highWarnRecord, MessageType.HIGHHREAT);
                            sendSMS(highWarnRecord, MessageType.HIGHHREAT);
                            RedisUtil.set(String.valueOf(highWarnRecord.getId()), "大于120", 60 * 30L);
                        }
                    }
                    // 如果脉搏在110-120 并且时间在20分钟以内
                    else if (Integer.parseInt(heartNum) <= 120 && Integer.parseInt(heartNum) > 110 && highWarnRecord.getCreateTime().after(getDate(start, 1000 * 60 * 20L))) {
                        // 判断用户id 为中级的次数 , 判断单号是否保存过 , 如果已经保存了 , 不能将次数加1
                        String userFlag = RedisUtil.get(highWarnRecord.getUserId() + "中", String.class);
                        if (userFlag == null) {
                            if (warnId == null) {
                                RedisUtil.set(highWarnRecord.getUserId() + "中", "1", 10L);
                            }
                        } else if (userFlag.equals("1") && warnId == null) {
                            // 如果单号为空 说明没有保存过
                            saveMessage(highWarnRecord, MessageType.HIGHHREAT);
                            long timeDiff = highWarnRecord.getCreateTime().getTime() - start.getTime();
                            RedisUtil.set(String.valueOf(highWarnRecord.getId()), "已保存", timeDiff / 1000);
                        }
                    } else if (Integer.parseInt(heartNum) <= 110 && Integer.parseInt(heartNum) > 100) {
                        // 判断用户id 为中级的次数 , 判断单号是否保存过 , 如果已经保存了 , 不能将次数加1
                        String userFlag = RedisUtil.get(highWarnRecord.getUserId() + "低", String.class);
                        if (userFlag == null) {
                            if (warnId == null) {
                                RedisUtil.set(highWarnRecord.getUserId() + "低", "1", 10L);
                            }
                        } else if (userFlag.equals("1") && warnId == null) {
                            RedisUtil.set(highWarnRecord.getUserId() + "低", "2", 10L);
                        } else if (userFlag.equals("2") && warnId == null) {
                            // 如果单号为空 说明没有保存过
                            saveMessage(highWarnRecord, MessageType.HIGHHREAT);
                            wxMessageService.sendWarnMessageToGzh(highWarnRecord.getUserId(),MessageType.HIGHHREAT,highWarnRecord.getCheckTime(),EquipCategory.getName(highWarnRecord.getDeviceType()));
                            long timeDiff = highWarnRecord.getCreateTime().getTime() - start.getTime();
                            RedisUtil.set(String.valueOf(highWarnRecord.getId()), "已保存", timeDiff / 1000);
                        }
                    } else if (Integer.parseInt(heartNum) < 50) {
                        if (warnId == null) {
                            // 保存数据库
                            saveMessage(highWarnRecord, MessageType.LOWHREAT);
                            wxMessageService.sendWarnMessageToGzh(highWarnRecord.getUserId(),MessageType.LOWHREAT,highWarnRecord.getCheckTime(),EquipCategory.getName(highWarnRecord.getDeviceType()));
                            // 发送短信
//                            sendSMS(highWarnRecord, MessageType.LOWHREAT);
                            RedisUtil.set(String.valueOf(highWarnRecord.getId()), "1", 60 * 30L);
                        }
                    } else if (Integer.parseInt(heartNum) <= 60 && Integer.parseInt(heartNum) >= 50) {
                        String userId3 = RedisUtil.get(highWarnRecord.getUserId() + "低", String.class);
                        if (userId3 == null) {
                            if (warnId == null) {
                                RedisUtil.set(highWarnRecord.getUserId() + "低", "1", 10L);
                            }
                        } else if (userId3.equals("1")) {
                            if (warnId == null) {
                                RedisUtil.set(highWarnRecord.getUserId() + "低", "2", 10L);
                            }
                        } else if (userId3.equals("2") && warnId == null) {
                            // 如果单号为空 说明没有保存过
                            saveMessage(highWarnRecord, MessageType.LOWHREAT);
                            wxMessageService.sendWarnMessageToGzh(highWarnRecord.getUserId(),MessageType.LOWHREAT,highWarnRecord.getCheckTime(),EquipCategory.getName(highWarnRecord.getDeviceType()));
                            long timeDiff = highWarnRecord.getCreateTime().getTime() - start.getTime();
                            RedisUtil.set(String.valueOf(highWarnRecord.getId()), "已保存", 30 * 60L);
                        }
                    }
                }
            }

            //查询体温数据
            List<HealthWarnRecord> tempWarnRecords = healthWarnRecordMapper.findTemperature(start, end);
            if (tempWarnRecords.size() > 0) {
                for (HealthWarnRecord tempWarnRecord : tempWarnRecords) {
                    String detail = tempWarnRecord.getDetail();
                    String replace = detail.replace("体温 (", "");
                    String heartNum = replace.replace(") 异常", "");
                    String tempId = RedisUtil.get(String.valueOf(tempWarnRecord.getId()), String.class);
                    if (Double.parseDouble(heartNum) > 39.5) {
                        if (tempId == null) {
                            saveMessage(tempWarnRecord, MessageType.HIGHTEMP);
                            wxMessageService.sendWarnMessageToGzh(tempWarnRecord.getUserId(),MessageType.HIGHTEMP,tempWarnRecord.getCheckTime(),EquipCategory.getName(tempWarnRecord.getDeviceType()));
                            // 发送短信
                            sendSMS(tempWarnRecord, MessageType.HIGHTEMP);
                            RedisUtil.set(String.valueOf(tempWarnRecord.getId()), "1", 60 * 30L);
                        }
                    } else if (Double.parseDouble(heartNum) <= 39.5 && Double.parseDouble(heartNum) > 38.5 && tempWarnRecord.getCreateTime().after(getDate(start, 1000 * 60 * 20L))) {
                        // 判断用户id 为中级的次数 , 判断单号是否保存过 , 如果已经保存了 , 不能将次数加1
                        String userFlag = RedisUtil.get(tempWarnRecord.getUserId() + "体中", String.class);
                        if (userFlag == null) {
                            if (tempId == null) {
                                RedisUtil.set(tempWarnRecord.getUserId() + "体中", "1", 10L);
                            }
                        } else if (userFlag.equals("1") && tempId == null) {
                            // 如果单号为空 说明没有保存过
                            saveMessage(tempWarnRecord, MessageType.MIDTEMP);
                            wxMessageService.sendWarnMessageToGzh(tempWarnRecord.getUserId(),MessageType.MIDTEMP,tempWarnRecord.getCheckTime(),EquipCategory.getName(tempWarnRecord.getDeviceType()));
                            long timeDiff = tempWarnRecord.getCreateTime().getTime() - start.getTime();
                            RedisUtil.set(String.valueOf(tempWarnRecord.getId()), "已保存", 30 * 60L);
                        }
                    } else if (Double.parseDouble(heartNum) <= 38.5 && Double.parseDouble(heartNum) > 37.5 && tempWarnRecord.getCreateTime().after(getDate(start, 1000 * 60 * 20L))) {
                        // 判断用户id 为中级的次数 , 判断单号是否保存过 , 如果已经保存了 , 不能将次数加1
                        String userFlag = RedisUtil.get(tempWarnRecord.getUserId() + "体低", String.class);
                        if (userFlag == null) {
                            if (tempId == null) {
                                RedisUtil.set(tempWarnRecord.getUserId() + "体低", "1", 10L);
                            }
                        } else if (userFlag.equals("1") && tempId == null) {
                            RedisUtil.set(tempWarnRecord.getUserId() + "体低", "2", 10L);
                        } else if (userFlag.equals("2") && tempId == null) {
                            // 如果单号为空 说明没有保存过
                            saveMessage(tempWarnRecord, MessageType.LOWTEMP);
                            wxMessageService.sendWarnMessageToGzh(tempWarnRecord.getUserId(),MessageType.LOWTEMP,tempWarnRecord.getCheckTime(),EquipCategory.getName(tempWarnRecord.getDeviceType()));
                            long timeDiff = tempWarnRecord.getCreateTime().getTime() - start.getTime();
                            RedisUtil.set(String.valueOf(tempWarnRecord.getId()), "已保存", 30 * 60L);
                        }
                    }
                }
            }

            // 查询血氧数据
            List<HealthWarnRecord> BloodRecords = healthWarnRecordMapper.findBloodOxygen(start, end);
            if (BloodRecords.size() > 0) {
                for (HealthWarnRecord bloodRecord : BloodRecords) {
                    String detail = bloodRecord.getDetail();
                    String replace = detail.replace("血氧 (", "");
                    String heartNum = replace.replace(") 异常", "");
                    String warnId = RedisUtil.get(String.valueOf(bloodRecord.getId()), String.class);
                    if (warnId == null) {
                        saveMessage(bloodRecord, MessageType.HITHBLOODOXYGEN);
                        wxMessageService.sendWarnMessageToGzh(bloodRecord.getUserId(),MessageType.HITHBLOODOXYGEN,bloodRecord.getCheckTime(),EquipCategory.getName(bloodRecord.getDeviceType()));
//                            sendSMS(bloodRecord, MessageType.HIGHHREAT);
                        RedisUtil.set(String.valueOf(bloodRecord.getId()), "血氧过高", 60 * 30L);
                    }
                }
            }
        }

        //    查询手表摘除 / 关机 / 电量 / SOS
        Integer newCount = warningMapper.getAllCount();
        Integer watchCount = RedisUtil.get("watchCount", Integer.class);
        if (watchCount == null || newCount > watchCount) {
            RedisUtil.set("watchCount", newCount);
            List<Warning> warnings = warningMapper.findWatchWarning(start, end);
            if (warnings.size() > 0) {
                for (Warning warning : warnings) {
                    Date createTime = Date.from(warning.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                    // SOS
                    String watchId = RedisUtil.get(warning.getId(), String.class);
                    if (warning.getType().equals("19")) {
                        if (watchId == null) {
                            saveWatchMessage(warning, MessageType.SOS);
                            sendSOSSMS(warning, MessageType.SOS);
                            wxMessageService.sendWarnMessageToGzh(warning.getCustomerId(),"SOS报警",createTime,EquipCategory.getName(warning.getCategory()));
                            RedisUtil.set(warning.getId(), "SOS报警", 60 * 30L);
                        }
                    }
                    // 摘除
                    else if (warning.getType().equals("21")) {
                        if (watchId == null) {
                            saveWatchMessage(warning, MessageType.REMOVE);
                            wxMessageService.sendWarnMessageToGzh(warning.getCustomerId(),"摘除报警",createTime,EquipCategory.getName(warning.getCategory()));
                            RedisUtil.set(warning.getId(), "摘除", 60 * 30L);
                        }
                        // 判断用户id 为中级的次数 , 判断单号是否保存过 , 如果已经保存了 , 不能将次数加1
                        /*String customerflag = RedisUtil.get(warning.getCustomerId() + "摘除", String.class);
                        if (customerflag == null) {
                            if (watchId == null) {
                                RedisUtil.set(warning.getCustomerId() + "摘除", "1", 10L);
                            }
                        } else if (customerflag.equals("1") && watchId == null) {
                            RedisUtil.set(warning.getCustomerId() + "摘除", "2", 10L);
                        } else if (customerflag.equals("2") && watchId == null) {
                            // 如果单号为空 说明没有保存过
                            saveWatchMessage(warning, MessageType.REMOVE);
                            long timeDiff = createTime.getTime() - start.getTime();
                            RedisUtil.set(warning.getId(), "已保存", 30*60L);
                        }*/
                    }
                    // 关机
                    else if (warning.getType().equals("20")) {
                        String customerflag = RedisUtil.get(warning.getCustomerId() + "关机", String.class);
                        if (watchId == null && customerflag == null) {
                            saveWatchMessage(warning, MessageType.SHUTDOWN);
                            wxMessageService.sendWarnMessageToGzh(warning.getCustomerId(),"关机报警",createTime,EquipCategory.getName(warning.getCategory()));
                            RedisUtil.set(warning.getCustomerId() + "关机", "1", 60 * 10L);
                            RedisUtil.set(warning.getId(), "已保存", 60 * 30L);
                        }

                        /*// 判断用户id 为中级的次数 , 判断单号是否保存过 , 如果已经保存了 , 不能将次数加1
                        String customerflag = RedisUtil.get(warning.getCustomerId() + "关机", String.class);
                        if (customerflag == null) {
                            if (watchId == null) {
                                RedisUtil.set(warning.getCustomerId() + "关机", "1", 10L);
                            }
                        } else if (customerflag.equals("1") && watchId == null) {
                            RedisUtil.set(warning.getCustomerId() + "关机", "2", 10L);
                        } else if (customerflag.equals("2") && watchId == null) {
                            // 如果单号为空 说明没有保存过
                            saveWatchMessage(warning, MessageType.SHUTDOWN);
                            sendSOSSMS(warning, MessageType.SHUTDOWN);
                            long timeDiff = createTime.getTime() - start.getTime();
                            RedisUtil.set(warning.getId(), "已保存", 30*60L);
                        }*/
                    }
                    //低电量
                    else if (warning.getType().equals("18")) {
                        String customerflag = RedisUtil.get(warning.getCustomerId() + "低电量", String.class);
                        if (watchId == null && customerflag == null) {
                            saveWatchMessage(warning, MessageType.LOWPOWER);
                            wxMessageService.sendWarnMessageToGzh(warning.getCustomerId(),"低电量报警",createTime,EquipCategory.getName(warning.getCategory()));
                            RedisUtil.set(warning.getCustomerId() + "低电量", "1", 60 * 10L);
                            RedisUtil.set(warning.getId(), "已保存", 60 * 30L);
                        }

                       /* String customerflag = RedisUtil.get(warning.getCustomerId() + "低电量", String.class);
                        if (customerflag == null) {
                            if (watchId == null) {
                                RedisUtil.set(warning.getCustomerId() + "低电量", "1", 10L);
                            }
                        } else if (customerflag.equals("1") && watchId == null) {
                            RedisUtil.set(warning.getCustomerId() + "低电量", "2", 10L);
                        } else if (customerflag.equals("2") && watchId == null) {
                            // 如果单号为空 说明没有保存过
                            saveWatchMessage(warning, MessageType.LOWPOWER);
                            long timeDiff = createTime.getTime() - start.getTime();
                            RedisUtil.set(warning.getId(), "已保存", 30*60L);
                        }*/
                    }
                }
            }
        }
    }

    private void sendSMS(HealthWarnRecord highWarnRecord, String type) {

       /* try {
            if (type.contains("心率")) {
                Map<String, String> map = new HashMap<String, String>();
                String templateCode = "SMS_225367056";
                HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(highWarnRecord.getUserId());
                Customer customer = customerService.selectCustomerById(self.getCustomerId());
                if (StringUtil.isBlank(customer.getPhone())) {
                    return;
                }
                sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                // 控制台创建的模板CODE
                sendSmsRequest.setTemplateCode(templateCode);
                String selfName = getName(self);
                map.put("name", selfName);//消息
                map.put("status", type.substring(2, 4));//消息
                map.put("phone", "968008");//消息
                sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                SendSmsResponse httpResponse = iAcsClient.getAcsResponse(sendSmsRequest);

                // 给关联人发送短信
                List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(highWarnRecord.getUserId());
                if (healthMessages.size() <= 0) {
                    return;
                }
                for (HealthMessage healthMessage : healthMessages) {
                    map = new HashMap<String, String>();
                    templateCode = "SMS_225386857";
                    // 关联亲人消息保存
                    HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                    customer = customerService.selectCustomerById(other.getCustomerId());
                    sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                    // 控制台创建的模板CODE
                    sendSmsRequest.setTemplateCode(templateCode);
                    String otherName = getName(other);
                    map.put("name", otherName);//消息
                    map.put("relation", "关联人" + selfName);//消息
                    map.put("status", type.substring(2, 4));//消息
                    map.put("phone", "968008");//消息
                    sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                    iAcsClient.getAcsResponse(sendSmsRequest);
                }
            } else if
            (type.contains("体温")) {
                Map<String, String> map = new HashMap<String, String>();
                String templateCode = "SMS_225367058";
                HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(highWarnRecord.getUserId());
                Customer customer = customerService.selectCustomerById(self.getCustomerId());
                if (StringUtil.isBlank(customer.getPhone())) {
                    return;
                }
                sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                // 控制台创建的模板CODE
                sendSmsRequest.setTemplateCode(templateCode);
                String selfName = getName(self);
                map.put("name", selfName);//消息
                map.put("phone", "968008");//消息
                sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                SendSmsResponse httpResponse = iAcsClient.getAcsResponse(sendSmsRequest);

                // 给关联人发送短信
                List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(highWarnRecord.getUserId());
                if (healthMessages.size() <= 0) {
                    return;
                }
                for (HealthMessage healthMessage : healthMessages) {
                    map = new HashMap<String, String>();
                    templateCode = "SMS_225386859";
                    // 关联亲人消息保存
                    HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                    customer = customerService.selectCustomerById(other.getCustomerId());
                    sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                    // 控制台创建的模板CODE
                    sendSmsRequest.setTemplateCode(templateCode);
                    String otherName = getName(other);
                    map.put("name", otherName);//消息
                    map.put("relation", "关联人" + selfName);//消息
                    map.put("phone", "968008");//消息
                    sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                    iAcsClient.getAcsResponse(sendSmsRequest);
                }

            }
        } catch (ClientException e) {
            System.out.println("error_短信发送失败");
            e.printStackTrace();
        }*/
    }

    private void sendSOSSMS(Warning warning, String type) {

        /*try {
            if (type.contains("关机")) {
                Map<String, String> map = new HashMap<String, String>();
                String templateCode = "SMS_225381859";
                HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(warning.getCustomerId());
                Customer customer = customerService.selectCustomerById(self.getCustomerId());
                if (customer.getPhone() == null) {
                    return;
                }
                sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                // 控制台创建的模板CODE
                sendSmsRequest.setTemplateCode(templateCode);
                String selfName = getName(self);
                map.put("name", selfName);//消息
                map.put("phone", "968008");//消息
                sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                SendSmsResponse httpResponse = iAcsClient.getAcsResponse(sendSmsRequest);

                // 给关联人发送短信
                List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(warning.getCustomerId());
                if (healthMessages.size() <= 0) {
                    return;
                }
                for (HealthMessage healthMessage : healthMessages) {
                    map = new HashMap<String, String>();
                    templateCode = "SMS_225381860";
                    // 关联亲人消息保存
                    HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                    customer = customerService.selectCustomerById(other.getCustomerId());
                    if (customer.getPhone() == null) {
                        return;
                    }
                    sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                    // 控制台创建的模板CODE
                    sendSmsRequest.setTemplateCode(templateCode);
                    String otherName = getName(other);
                    map.put("name", otherName);//消息
                    map.put("relation", "关联人" + selfName);//消息
                    map.put("phone", "968008");//消息
                    sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                    iAcsClient.getAcsResponse(sendSmsRequest);
                }
            } else if (type.contains("SOS")) {
                String templateCode = "SOS模板";
                HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(warning.getCustomerId());
                String selfName = getName(self);
                // 给关联人发送短信
                List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(warning.getCustomerId());
                if (healthMessages.size() <= 0) {
                    return;
                }
                for (HealthMessage healthMessage : healthMessages) {
                    Map<String, String> map = new HashMap<String, String>();
                    templateCode = "SMS_225381857";
                    // 关联亲人消息保存
                    HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                    if (other == null) {
                        return;
                    }
                    Customer customer = customerService.selectCustomerById(other.getCustomerId());
                    if (customer.getPhone() == null) {
                        return;
                    }
                    sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
                    // 控制台创建的模板CODE
                    sendSmsRequest.setTemplateCode(templateCode);
                    String otherName = getName(other);
                    map.put("name", otherName);//消息
                    map.put("relation", "关联人" + selfName);//消息
                    map.put("phone", "968008");//消息
                    sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                    iAcsClient.getAcsResponse(sendSmsRequest);
                }
            }
        } catch (ClientException e) {
            System.out.println("error_短信发送失败");
            e.printStackTrace();
        }*/
    }

    private void saveWatchMessage(Warning warning, String type) {
        HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(warning.getCustomerId());
        // 保存数据库
        self.setId(UUID.randomUUID().toString());
        self.setType(type);
        Date createTime = Date.from(warning.getCreateTime().atZone(ZoneId.systemDefault()).toInstant());
        String selfName = getName(self);
        String sexs = self.getSex() == 0 ? "女士" : "先生";
        String categoryStr = "设备";
        if (warning.getCategory().equals("4")) {
            categoryStr = "M99手表";
        }else if (warning.getCategory().equals("5")) {
            categoryStr = "手环";
        } else if (warning.getCategory().equals("12")) {
            categoryStr = "手表";
        }
        if (type.equals(MessageType.REMOVE)) {
            self.setContent("尊敬的" + selfName + sexs + "您好：\n" + "安博馨监测到您的智能健康"+categoryStr+"已摘除，请及时佩戴。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
        } else if (type.equals(MessageType.SHUTDOWN)) {
            self.setContent("尊敬的" + selfName + sexs + "您好：\n" + "安博馨监测到您的"+categoryStr+"已关机。请及时开机，如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
        } else if (type.equals(MessageType.LOWPOWER)) {
            self.setContent("尊敬的" + selfName + sexs + "您好：\n" + "安博馨监测到您"+categoryStr+"电量过低。请及时充电，如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
        } else if (type.equals(MessageType.SOS)) {
            self.setContent("尊敬的" + selfName + sexs + "您好：\n" + "安博馨监测到您发出了SOS求助提醒");
        }

        self.setCrateTime(createTime);

        healthWarnRecordMapper.insertMessage(self);

        // 获取关联人信息
        List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(warning.getCustomerId());
        if (healthMessages.size() <= 0) {
            return;
        }
        for (HealthMessage healthMessage : healthMessages) {
            // 关联亲人消息保存
            HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
            if (other != null) {
                other.setId(UUID.randomUUID().toString());
                other.setType(type);
                String otherName = getName(other);
                sexs = other.getSex() == 0 ? "女士" : "先生";
                if (type.equals(MessageType.REMOVE)) {
                    other.setContent("尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + " 的智能健康"+categoryStr+"已摘除，须及时佩戴。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
                } else if (type.equals(MessageType.SHUTDOWN)) {
                    other.setContent("尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + " 的智能健康"+categoryStr+"电量过低，须及时充电。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
                } else if (type.equals(MessageType.LOWPOWER)) {
                    other.setContent("尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + " 的智能健康"+categoryStr+"已关机，须及时开机。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
                } else if (type.equals(MessageType.SOS)) {
                    other.setContent("尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + " 的智能健康"+categoryStr+"SOS一键求助，我们会提供协助。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
                }
                other.setRelateId(warning.getCustomerId());
                other.setCrateTime(createTime);
                healthWarnRecordMapper.insertMessage(other);
            }
        }
    }

    private String getName(HealthMessage self) {
        String selfName = self.getUsername();

        if (StringUtil.isNotBlank(selfName)) {
            if (selfName.contains("（")) {
                selfName = selfName.split("（")[0];
                self.setUsername(selfName);
            }
        } else {
            selfName = "用户";
        }
        return selfName;
    }

    private void saveMessage(HealthWarnRecord highWarnRecord, String type) {
        if (type.contains("心率")) {
            HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(highWarnRecord.getUserId());
            // 保存数据库
            if (self == null) {
                return;
            }
            self.setId(UUID.randomUUID().toString());
            self.setType(type);
            String selfName = getName(self);
            String sexs = self.getSex() == 0 ? "女士" : "先生";
            self.setContent("尊敬的" + selfName + sexs + "您好!\n" + "安博馨监测到您的" + type + "。请保持心情愉悦、不要过分劳累。如需帮助，请拨打24小时人工守护中心联系电话（ 968008 ）。");
            self.setCrateTime(new Date());
            healthWarnRecordMapper.insertMessage(self);

            List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(highWarnRecord.getUserId());
            if (healthMessages.size() <= 0) {
                return;
            }
            for (HealthMessage healthMessage : healthMessages) {
                // 关联亲人消息保存
                HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                if (other != null) {
                    other.setId(UUID.randomUUID().toString());
                    other.setType(type);
                    String otherName = getName(other);
                    sexs = other.getSex() == 0 ? "女士" : "先生";
                    // 关系  暂时用关联人代替
                    String relation = healthMessage.getRelation();
                    other.setContent("尊敬的" + otherName + sexs + "您好！\n" + "安博馨监测到您的" + "关联人 " + selfName + type + "。需保持心情愉悦、不要过分劳累。如需帮助，请拨打24小时人工守护中心联系电话（ 968008 ）。");
                    other.setRelateId(highWarnRecord.getUserId());
                    other.setCrateTime(new Date());
                    healthWarnRecordMapper.insertMessage(other);
                }
            }
        }
        if (type.contains("体温")) {
            HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(highWarnRecord.getUserId());
            // 保存数据库
            if (self == null) {
                return;
            }
            self.setId(UUID.randomUUID().toString());
            self.setType(type);
            String selfName = getName(self);
            String sexs = self.getSex() == 0 ? "女士" : "先生";
            String textType = type;
            self.setContent(type + "提醒:\n" + "尊敬的" + selfName + sexs + "您好!\n" + "安博馨监测到您" + textType + "，请您多饮水、勤测体温。如需帮助，请拨打24小时人工守护中心电话（ 968008 ）。");
            if (type.equals(MessageType.MIDTEMP)) {
                textType = "体温中度发热";
                self.setContent(type + "提醒:\n" + "尊敬的" + selfName + sexs + "您好!\n" + "安博馨监测到您" + textType + "，请您多饮水、勤测体温。如需帮助，请拨打24小时人工守护中心电话（ 968008 ）。");
            }
            if (type.equals(MessageType.HIGHTEMP)) {
                textType = "体温异常";
                self.setContent(type + "提醒:\n" + "尊敬的" + selfName + sexs + "您好!\n" + "安博馨监测到您" + textType + "，请立即就医。如需帮助，请拨打24小时人工守护中心电话（968008）。");
            }
            self.setCrateTime(new Date());
            healthWarnRecordMapper.insertMessage(self);

            List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(highWarnRecord.getUserId());
            if (healthMessages.size() <= 0) {
                return;
            }
            for (HealthMessage healthMessage : healthMessages) {
                // 关联亲人消息保存
                HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                if (other != null) {
                    other.setId(UUID.randomUUID().toString());
                    other.setType(type);
                    String otherName = getName(other);
                    sexs = other.getSex() == 0 ? "女士" : "先生";
                    other.setContent(type + "提醒:\n" + "尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + type + "，须多饮水、勤测温。如需帮助，请拨打24小时人工守护中心电话（968008）。");
                    if (type.equals(MessageType.MIDTEMP)) {
                        textType = "体温中度发热";
                        other.setContent(type + "提醒:\n" + "尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + textType + "，须多饮水、勤测温。如需帮助，请拨打24小时人工守护中心电话（968008）。");
                    }
                    if (type.equals(MessageType.HIGHTEMP)) {
                        textType = "体温异常";
                        other.setContent(type + "提醒:\n" + "尊敬的" + otherName + sexs + "您好!\n" + "安博馨监测到您的" + "关联人 " + selfName + textType + "，请立即就医。如需帮助，请拨打24小时人工守护中心电话（968008）。");
                    }
                    other.setRelateId(highWarnRecord.getUserId());
                    other.setCrateTime(new Date());
                    healthWarnRecordMapper.insertMessage(other);
                }
            }
        }
        if (type.contains("血氧")) {
            HealthMessage self = healthWarnRecordMapper.getUsernameAndSex(highWarnRecord.getUserId());
            // 保存数据库
            if (self == null) {
                return;
            }
            self.setId(UUID.randomUUID().toString());
            self.setType(type);
            String selfName = getName(self);
            String sexs = self.getSex() == 0 ? "女士" : "先生";
            String textType = type;
            self.setContent("尊敬的" + selfName + sexs + "您好! " + "安博馨监测到您血氧饱和度异常，请您注意身体状况，保持所处环境空气流动畅通。如需帮助，请拨打24小时人工守护中心联系电话（ 968008 ）。");
            self.setCrateTime(new Date());
            healthWarnRecordMapper.insertMessage(self);

            List<HealthMessage> healthMessages = healthWarnRecordMapper.getRelateIdsByUserId(highWarnRecord.getUserId());
            if (healthMessages.size() <= 0) {
                return;
            }
            for (HealthMessage healthMessage : healthMessages) {
                // 关联亲人消息保存
                HealthMessage other = healthWarnRecordMapper.getUsernameAndSex(healthMessage.getCustomerId());
                if (other != null) {
                    other.setId(UUID.randomUUID().toString());
                    other.setType(type);
                    String otherName = getName(other);
                    sexs = other.getSex() == 0 ? "女士" : "先生";
                    other.setContent("尊敬的" + otherName + sexs + "您好! " + "安博馨监测到您的" + "关联人 " + selfName + "血氧饱和度异常，须注意身体状况，保持所处环境空气流动畅通。如需帮助，请拨打24小时人工守护中心联系电话（968008）。");
                    other.setRelateId(highWarnRecord.getUserId());
                    other.setCrateTime(new Date());
                    healthWarnRecordMapper.insertMessage(other);
                }
            }
        }
    }

    private Date getDate(Date start, Long amount) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strTime = sdf.format(start.getTime() - amount);
        return sdf.parse(strTime);
    }


    public void deleteOufuBandSleep() {
        List<OuFuData> list = bandSleepMapper.selectOufuBandSleep();
        OuFuDataExample example = new OuFuDataExample();
        for (OuFuData ouFuData : list) {
            Date checkTime = ouFuData.getCheckTime();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(checkTime);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date time = calendar.getTime();
            example.clear();
            example.createCriteria().andCustomerIdEqualTo(ouFuData.getCustomerId()).andCheckTimeLessThan(time);
            bandSleepMapper.deleteByExample(example);
        }
    }

    @Resource(name = "LbWebSocketClient")
    private LbWebSocketClient lbWebSocketClient;

    public void lbKeepAlive() {
        if (lbWatchService.startSendHeart) {
            lbWebSocketClient.send("{\"action\": \"keepAlive\"}");
        }
    }

    public void lbWatchInsertStep() {
        List<EquipmentCustomView> list = equipmentCustomMapper.selectBindLbWatchList();
        for (EquipmentCustomView ec : list) {
            lbWatchService.insertStep(ec.getLbUserid(), ec.getSerialNumber(), ec.getCustomerId());
        }
    }

    public void lbWatchInsertSleep() {
        List<EquipmentCustomView> list = equipmentCustomMapper.selectBindLbWatchList();
        for (EquipmentCustomView ec : list) {
            lbWatchService.insertSleep(ec.getLbUserid(), ec.getSerialNumber(), ec.getCustomerId());
        }
    }

    public void lbWatchInsertLoc() {
        List<EquipmentCustomView> list = equipmentCustomMapper.selectBindLbWatchList();
        for (EquipmentCustomView ec : list) {
            //开启查找长者
            lbWatchService.openFindElder(ec.getLbUserid());
        }

    }

    public void createHealthReport() {
        healthReportService.createHealthReport();
    }

    public void sendBirthdayMessage() {
        taskMessageService.sendBirthdayMessage();
    }

    public void sendFestivalMessage() throws ParseException {
        SimpleCalendar.Element element = SimpleCalendar.getCalendarDetail(new Date());
        String lunarFestival = element.getLunarFestival();
        if (lunarFestival.equals("中秋节")) {
            sendSMS("SMS_234031507");
        } else if (lunarFestival.equals("元旦")) {
            sendSMS("SMS_234041482");
        } else if (lunarFestival.equals("端午节")) {
            sendSMS("SMS_234051338");
        } else if (lunarFestival.equals("春节")) {
            sendSMS("SMS_234036464");
        } else if (lunarFestival.equals("重阳节")) {
            sendSMS("SMS_234031508");
        }
    }


    private void sendSMS(String templateCode) {
        List<Customer> list = customerService.selectCustomerList();
        for (Customer customer : list) {
            // 短信
            sendSmsRequest.setPhoneNumbers(customer.getPhone());   //接收号码
            // 控制台创建的模板CODE
            sendSmsRequest.setTemplateCode(templateCode);
            String name = StringUtil.isBlank(customer.getName()) ? "" : customer.getName();
            if (!templateCode.equals("SMS_234051338")) {
                HashMap<Object, Object> map = new HashMap<>();
                map.put("name", name);//消息
                sendSmsRequest.setTemplateParam(JSON.toJSONString(map));// 短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
            }
            try {
                SendSmsResponse httpResponse = iAcsClient.getAcsResponse(sendSmsRequest);
            } catch (Exception e) {
                log.error("节日短信发送失败："+e.toString());
            }
            //小程序
            HealthMessage msg = new HealthMessage();
            msg.setType("节日问候");
            msg.setCustomerId(customer.getId());
            msg.setId(UUID.randomUUID().toString());
            msg.setCrateTime(new Date());
            String content = getContent(templateCode, name);
            if (StringUtil.isBlank(content)) {
                return;
            }
            msg.setContent(content);
            healthWarnRecordMapper.insertMessage(msg);
        }
    }

    private String getContent(String templateCode, String name) {
        if (templateCode.equals("SMS_234031507")) {
            return "尊敬的" + name + "先生/女士，时值中秋佳节，广电安博馨愿您心想事成，阖家安康。";
        } else if (templateCode.equals("SMS_234041482")) {
            return "尊敬的" + name + "先生/女士，时值元旦之际，广电安博馨恭祝您及家人新年新气象，五福齐临门。";
        } else if (templateCode.equals("SMS_234051338")) {
            return "端午到，挂香包，吃粽子，家家户户真热闹！广电安博馨祝您端午安康。";
        } else if (templateCode.equals("SMS_234036464")) {
            return "尊敬的" + name + "先生/女士，时值新春佳节，广电安博馨祝您新年身体健康，快乐无疆！";
        } else if (templateCode.equals("SMS_234031508")) {
            return name + "先生/女士，酒越酒香意浓，九月九夕阳红，年年九月丹红，念念老人深情。广电安博馨祝您重阳节快乐！";
        }
        return "";
    }


    public void save72HourNoDataCustomerToRedis() {
        customerService.save72HourNoDataCustomerToRedis();
    }

    public void updateCommunityData() {
        Map map = healthWarnRecordMapper.selectCountForCommunity();
        RedisUtil.set("countForCommunity", map);
    }
}
